package org.jeecg.modules.miniAppCustomerEndPoint.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.hc.entity.HcMerchant;
import org.jeecg.modules.hc.entity.HcOrderDetailed;
import org.jeecg.modules.hc.entity.HcSiteRelation;
import org.jeecg.modules.hc.service.IHcMerchantService;
import org.jeecg.modules.hc.service.IHcOrderMerchantService;
import org.jeecg.modules.hc.service.IHcSiteRelationService;
import org.jeecg.modules.hc.utils.HcUtils;
import org.jeecg.modules.miniAppCustomerEndPoint.entity.JxFoodBriefDetailRespVo;
import org.jeecg.modules.miniAppCustomerEndPoint.entity.JxSiteMenuDo;
import org.jeecg.modules.miniAppCustomerEndPoint.entity.JxSiteStoreDo;
import org.jeecg.modules.miniAppCustomerEndPoint.entity.JxStoreCategoryDo;
import org.jeecg.modules.miniAppCustomerEndPoint.mapper.JxSiteMenuMapper;
import org.jeecg.modules.miniAppCustomerEndPoint.mapper.JxSiteStoreMapper;
import org.jeecg.modules.miniAppCustomerEndPoint.service.JxUserCouponServiceImpl;
import org.jeecg.modules.miniAppCustomerEndPoint.utils.JxUserUtil;
import org.jeecg.modules.platformMasterEndPoint.entity.JxFoodRepositoryDo;
import org.jeecg.modules.platformMasterEndPoint.entity.JxStoreRepositoryDo;
import org.jeecg.modules.platformMasterEndPoint.mapper.JxFoodRepositoryMapper;
import org.jeecg.modules.platformMasterEndPoint.mapper.JxStoreRepositoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 商户
 * @Author: jeecg-boot
 * @Date: 2022-12-13
 * @Version: V1.0
 */
@Api(tags = "店铺相关的操作")
@RestController
@RequestMapping("/jx/jxStore")
@Slf4j
public class JxStoreController extends JeecgController<HcMerchant, IHcMerchantService> {
    @Autowired
    private IHcMerchantService hcMerchantService;

    @Autowired
    private IHcOrderMerchantService hcOrderMerchantService;

    @Autowired
    private IHcSiteRelationService hcSiteRelationService;

    @Autowired
    private JxSiteMenuMapper jxSiteMenuMapper;

    @Autowired
    private JxSiteStoreMapper jxSiteStoreMapper;

    @Autowired
    private JxStoreRepositoryMapper jxStoreRepositoryMapper;

    @Autowired
    private JxFoodRepositoryMapper jxFoodRepositoryMapper;

    @Autowired
    private JxUserCouponServiceImpl jxUserCouponService;

    /**
     *  接口1.4 【首页】顶部的搜索框，根据用户所属的大厦和搜索关键字，查询符合搜索关键字的 店铺 和 菜品；
     * 注意区别和进入到店铺页面后，店铺页面内的 搜索框
     * @param siteId 用户所属站点id
     * @param keyword 搜索关键字
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "用户端首页获取商户和菜品列表", notes="两种场景下调用此接口：<br/>1. 当用户点击 https://www.yonghsantuan.com 打开点餐页面时;<br/> 2.当用户在点餐页面选择某个主品类时，比如中餐，轻食 ")
    @GetMapping("/queryStoresByKeyword")
    public Result<?> queryStoresByKeyword(@RequestParam("siteAddrId") String siteId,
                             HttpServletRequest request,
                             @RequestParam(value = "userId", required = false) String userIdForDebug,
                             @RequestParam("keyword") String keyword,
                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        String token = request.getHeader("X-Access-Token");
        String userId = null;
        if (token != null || userIdForDebug != null) {
            // todo request body 中的userId 不是必选项，只是调试时使用，正式上线时，需要去掉；
            // todo 可以使用其他人的用户id进行调试，每个用户使用微信登录时，才能获取到该用户的id，此处可以绕过此限制
            userId = JxUserUtil.getUserId(token, userIdForDebug);
        }
        // 此处和前端约定好，传递的 pageNo 从1开始，pageNo 不能为0 或负数； keyword可以为空字符串
        List<HashMap<String, Object>> foodList = jxSiteMenuMapper.queryFoodListByKeyword(siteId, keyword, (pageNo - 1) * pageSize, pageSize);
        // 用户输入的查询条件，可能匹配了来自多家店铺的菜品，找出符合客户搜索条件的所有菜品，来自哪些不同的店铺
        HashMap<String, List<JxFoodBriefDetailRespVo>> storeFoodMap = new HashMap<>();
        for (int i = 0 ; i < foodList.size() ; i ++) {
            HashMap<String,Object> oneFood = foodList.get(i);
            String storeId = (String)oneFood.get("storeId");
            JxFoodBriefDetailRespVo briefDetailRespVo = new JxFoodBriefDetailRespVo();
            String foodId = (String)oneFood.get("foodId");
            briefDetailRespVo.setFoodId(foodId);
            briefDetailRespVo.setFoodName((String)oneFood.get("foodName"));
            briefDetailRespVo.setFoodImage((String)oneFood.get("foodImage"));
            briefDetailRespVo.setSalePrice((Integer)oneFood.get("salePrice"));
            briefDetailRespVo.setLimitCount((Integer) oneFood.get("limitCount"));
            JxFoodRepositoryDo foodRepositoryDo = jxFoodRepositoryMapper.selectById(foodId);
            if (foodRepositoryDo == null) {
                log.error("菜品信息库表中无法查找到菜品id：{} 的菜品", foodId);
                continue;
            }
            briefDetailRespVo.setSpecifications(JSONArray.parseArray(foodRepositoryDo.getSpecification()));
            briefDetailRespVo.setSort((Integer)oneFood.get("sort"));

            if (storeFoodMap.containsKey(storeId)) {
                storeFoodMap.get(storeId).add(briefDetailRespVo);
            } else {
                List<JxFoodBriefDetailRespVo> oneStoreFoodList = new ArrayList<>();
                oneStoreFoodList.add(briefDetailRespVo);

                storeFoodMap.put(storeId, oneStoreFoodList);
            }
        }

        List<HashMap<String, Object>> formatedResultData = new ArrayList<>();
        Iterator<String> itr = storeFoodMap.keySet().iterator();
        while (itr.hasNext()) {
            String storeId = itr.next();
            List<JxSiteStoreDo> list = jxSiteStoreMapper.selectList(new LambdaQueryWrapper<JxSiteStoreDo>().eq(JxSiteStoreDo::getStoreId, storeId));
            if (list != null && list.size() > 0) {
                JxSiteStoreDo oneStore = list.get(0);
                HashMap<String, Object> storeDetail = new HashMap<>();
                storeDetail.put("storeId", storeId);
                // todo 此处频繁查询 jx_store_respository表，性能较差，后期需要将 店铺公共信息 存放在 redis中 jx_store_repo_xxxx -> {}
                JxStoreRepositoryDo storeRepositoryDo = jxStoreRepositoryMapper.selectById(storeId);
                storeDetail.put("storeName", storeRepositoryDo.getStoreName());
                storeDetail.put("storeDescription", storeRepositoryDo.getStoreDescription());
                storeDetail.put("storeLogo", storeRepositoryDo.getLogo());
                storeDetail.put("businessHoursBegin", storeRepositoryDo.getBusinessStart());
                storeDetail.put("businessHoursEnd", storeRepositoryDo.getBusinessEnd());

                storeDetail.put("qualifications", storeRepositoryDo.getQualifications());
                // 同一个店铺的 综合评分和总销量
                storeDetail.put("score", oneStore.getFlavorScore());
                storeDetail.put("sales", 218);
//                storeDetail.put("componentScore", oneStore.getComponentScore());
//                storeDetail.put("packagingScore", oneStore.getPackagingScore());
                storeDetail.put("foods", storeFoodMap.get(storeId));
                List<JSONObject> avaliableCoupons = jxUserCouponService.checkAvailiableCouponsByStoreId(siteId, storeId, userId);
                storeDetail.put("coupons", avaliableCoupons);
                formatedResultData.add(storeDetail);
            } else {
                log.error("无法从 store表中查询到 店铺id为 {} 的详情", storeId);
            }
        }

        return Result.ok(formatedResultData);
    }

    /**
     * 店铺内搜索框，搜索符合条件的菜品，可能来自不同的分类，因此小程序在展示搜索结果时，应该显示在 【点餐】 tab页内，而不是具体的某一个分类的tab页内
     * @param siteId
     * @param storeId
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "店铺内搜索框", notes="点击进入店铺，店铺内搜索框根据输入的关键字，搜索返回菜品")
    @GetMapping("/queryFoodsByKeyword")
    public Result<?> queryFoodsByKeyword(
            @RequestParam("siteId") String siteId,
            @RequestParam("storeId") String storeId,
            @RequestParam("keyword") String keyword,
            @RequestParam("pageNo") Integer pageNo,
            @RequestParam("pageSize") Integer pageSize) {

        JSONObject resultData = new JSONObject();
        JSONArray formatedFoods = new JSONArray();
        Integer totalCount = jxFoodRepositoryMapper.queryFoodsWithKeywordPageInfo(siteId, storeId, keyword);
        if (totalCount > 0) {
            List<HashMap<String, Object>> pageList = jxFoodRepositoryMapper.queryFoodsWithKeywordByPage(siteId, storeId, keyword, (pageNo - 1) * pageSize, pageSize);
            formatedFoods = buildFoodListInStore(pageList);
        }
        int pages = totalCount / pageSize == 0 ? totalCount / pageSize : (totalCount / pageSize + 1);
        resultData.put("totalCount", totalCount);
        resultData.put("pages", pages);
        resultData.put("foods", formatedFoods);

        return Result.ok(resultData);
    }

    @ApiOperation(value = "查询店铺分类", notes="首页搜索框下的几个店铺分类按钮，各个大厦展示的店铺品类可能会不同")
    @GetMapping("/queryStoreCategories")
    public Result<?> queryStoreCategories(@RequestParam("siteAddrId") String siteAddrId) {
        List<JxStoreCategoryDo> list = jxSiteStoreMapper.queryStoreCategories(siteAddrId);
        List<HashMap<String, Object>> formatedStoreCategories = list.stream().map(item -> {
            HashMap<String, Object> formatedCategory = new HashMap<>();
            formatedCategory.put("categoryId", item.getId());
            formatedCategory.put("categoryName", item.getName());
            formatedCategory.put("image", item.getIcon());
            formatedCategory.put("sort", item.getSort());
            return formatedCategory;
        }).collect(Collectors.toList());

        return Result.ok(formatedStoreCategories);
    }

    @ApiOperation(value = "获取特定类别的店铺列表", notes="点击首页搜索框下的几个店铺分类按钮，获取不同类别的店铺")
    @GetMapping("/queryStoresByCategoriyId")
    public Result<?> queryStoresByCategoryId(
            HttpServletRequest request,
            @RequestParam(value = "userId", required = false) String userId,
            @RequestParam("siteId") String siteId, @RequestParam("categoryId") String categoryId) {
        String token = request.getHeader("X-Access-Token");
        // todo request body 中的userId 不是必选项，只是调试时使用，正式上线时，需要去掉；
        // todo 可以使用其他人的用户id进行调试，每个用户使用微信登录时，才能获取到该用户的id，此处可以绕过此限制
        String userId2 = JxUserUtil.getUserId(token, userId);
        // select * from jx_store where site_address_id = xxx and store_category_id = xxx;
        List<JxSiteStoreDo> storeList = jxSiteStoreMapper.selectList(new LambdaQueryWrapper<JxSiteStoreDo>().eq(JxSiteStoreDo::getSiteId, siteId));
        List<HashMap<String, Object>> formatedResultData = new ArrayList<>();
        for (int i = 0 ; i < storeList.size() ; i ++) {
            JxSiteStoreDo siteStoreDo = storeList.get(i);
            JxStoreRepositoryDo storeRepositoryDo = jxStoreRepositoryMapper.selectById(siteStoreDo.getStoreId());
            if (storeRepositoryDo == null) {
                log.error("店铺信息库中无法找到id为: {} 的店铺", siteStoreDo.getStoreId());
                continue;
            } else {
                if (!storeRepositoryDo.getCategoryId().equalsIgnoreCase(categoryId)) {
                    log.info("storeId: {}, storeName: {} 主品类类别不是 {}({}), 跳过此店铺", storeRepositoryDo.getId(), storeRepositoryDo.getStoreName(), storeRepositoryDo.getCategoryId(), storeRepositoryDo.getCategoryName());
                    continue;
                }
            }
            List<JxSiteMenuDo> foodList = jxSiteMenuMapper.selectList(
                    new LambdaQueryWrapper<JxSiteMenuDo>()
                            .eq(JxSiteMenuDo::getSiteId, siteId)
                            .eq(JxSiteMenuDo::getStoreId, siteStoreDo.getId())
                            .orderByAsc(JxSiteMenuDo::getSort).last(" limit 3"));

            // jx_site_address_menu表中有些菜品的字段不需要返回给前端，此处挑选一些重要的返回
            List<JxFoodBriefDetailRespVo> formatedFoodBreifDetailList = foodList.stream().map(item-> {
                // todo 需要将菜品基本信息缓存到 redis中，避免每次循环都执行一次db查询，性能会很差
                JxFoodRepositoryDo foodRepositoryDo = jxFoodRepositoryMapper.selectById(item.getFoodId());
                if (foodRepositoryDo == null) {
                    log.error("从菜品信息库表中，差找不到id为 {} 的菜品", item.getFoodId());
                    return null;
                }else {
                    JxFoodBriefDetailRespVo briefDetailRespVo = new JxFoodBriefDetailRespVo();
                    briefDetailRespVo.setFoodId(item.getFoodId());
                    briefDetailRespVo.setFoodName(foodRepositoryDo.getFoodName());
                    briefDetailRespVo.setFoodImage(foodRepositoryDo.getImage());
                    briefDetailRespVo.setLimitCount(item.getLimitCount());
                    briefDetailRespVo.setSort(item.getSort());
                    return briefDetailRespVo;
                }
            }).collect(Collectors.toList());

            HashMap<String, Object> storeDetail = formateStoreBasicInfo(siteStoreDo, storeRepositoryDo);
            List<JSONObject> coupons = jxUserCouponService.checkAvailiableCouponsByStoreId(siteId, siteStoreDo.getStoreId(), userId2);
            storeDetail.put("coupons", coupons);
            storeDetail.put("foods", formatedFoodBreifDetailList);

            formatedResultData.add(storeDetail);
        }

        return Result.ok(formatedResultData);
    }

    private HashMap<String, Object> formateStoreBasicInfo(JxSiteStoreDo siteStoreDo, JxStoreRepositoryDo storeRepositoryDo) {
        HashMap<String, Object> storeBasicInfo = new HashMap<>();
        storeBasicInfo.put("storeId", siteStoreDo.getId());
        storeBasicInfo.put("storeName", storeRepositoryDo.getStoreName());
        storeBasicInfo.put("storeDescription", storeRepositoryDo.getStoreDescription());
        storeBasicInfo.put("storeLogo", storeRepositoryDo.getLogo());
        storeBasicInfo.put("businessHoursBegin", storeRepositoryDo.getBusinessStart());
        storeBasicInfo.put("businessHoursEnd", storeRepositoryDo.getBusinessEnd());
        storeBasicInfo.put("qualifications", storeRepositoryDo.getQualifications());
        storeBasicInfo.put("flavorScore", siteStoreDo.getFlavorScore());
        storeBasicInfo.put("componentScore", siteStoreDo.getComponentScore());
        storeBasicInfo.put("packagingScore", siteStoreDo.getPackagingScore());

        return storeBasicInfo;
    }

    /**
     * 接口1.12 点击 某个店铺，进入店铺内后，该接口将返回如下3种数据
     * 第1部分数据，店铺基本信息，以及店铺中可以领取的优惠券
     * 第2部分数据，店铺的菜品分类，左侧店铺导航栏
     * 第3部分数据，默认选中的菜品分类及该分类的菜品数据
     * @param request
     * @param userIdForDebug
     * @param siteId
     * @param storeId
     * @return
     */
    @ApiOperation(value = "点击进入店铺，获取店铺详情及菜品分类列表", notes="点击进入店铺，获取店铺详情及菜品分类列表")
    @GetMapping("/queryStoreDetail")
    public Result<?> queryStoreDetail(
            HttpServletRequest request,
            @RequestParam(value = "userId", required = false) String userIdForDebug,
            @RequestParam("siteId") String siteId,
            @RequestParam("storeId") String storeId) {
        String token = request.getHeader("X-Access-Token");
        // todo request body 中的userId 不是必选项，只是调试时使用，正式上线时，需要去掉；
        // todo 可以使用其他人的用户id进行调试，每个用户使用微信登录时，才能获取到该用户的id，此处可以绕过此限制
        String userId = JxUserUtil.getUserId(token, userIdForDebug);
        LambdaQueryWrapper<JxSiteMenuDo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(JxSiteMenuDo::getSiteId, siteId).eq(JxSiteMenuDo::getStoreId, storeId).eq(JxSiteMenuDo::getState, "yes").eq(JxSiteMenuDo::getDelFlag, 0);
        List<JxSiteMenuDo> list = jxSiteMenuMapper.selectList(lambdaQueryWrapper);
        HashMap<String, List<JSONObject>> groupedFoods = new HashMap<>();
        if (list != null && list.size() > 0) {
            // 将某个店铺为某个站点供应的菜品，按照菜品类型进行分类
            for (int k = 0 ; k < list.size(); k ++) {
                JxSiteMenuDo siteMenuDo = list.get(k);
                JxFoodRepositoryDo foodRepositoryDo = jxFoodRepositoryMapper.selectById(siteMenuDo.getFoodId());
                if (foodRepositoryDo == null) {
                    log.error("菜品 {} 不存在", siteMenuDo.getFoodId());
                    continue;
                }
                String foodType = foodRepositoryDo.getFoodTypeName();
                if (!groupedFoods.containsKey(foodType)) {
                    groupedFoods.put(foodType, new ArrayList<>());
                }
                JSONObject formatedFoodInfo = buildOneFoodInStore(siteMenuDo, foodRepositoryDo);
                groupedFoods.get(foodType).add(formatedFoodInfo);
            }

            HashMap<String,Object> formatedData = new HashMap<>();
            // 第1部分数据，店铺基本信息，以及店铺中可以领取的优惠券
            formatedData.put("storeId", storeId);
            JxStoreRepositoryDo storeRepositoryDo = jxStoreRepositoryMapper.selectById(storeId);
            formatedData.put("storeName", storeRepositoryDo.getStoreName());
            formatedData.put("storeDescription", storeRepositoryDo.getStoreDescription());
            formatedData.put("logo", storeRepositoryDo.getLogo());
            JSONArray foodTypes = JSONArray.parseArray(storeRepositoryDo.getFoodTypes());
            // 每个店铺都必须有一个 点菜 分类，如果在管理平台端没有配置，则默认补充一个此 分类
            if (!foodTypes.contains("点餐")) {
                foodTypes.add(0, "点餐");
            }
            // 某些菜品分类没有配置菜品时，或配置的菜品下架时，该分类补充空数组 []
            for (int k = 0 ; k < foodTypes.size(); k ++) {
                String foodTypeName = foodTypes.getString(k);
                if (!groupedFoods.containsKey(foodTypeName)) {
                    groupedFoods.put(foodTypeName, new ArrayList<>());
                }
            }

            List<JSONObject> coupons = jxUserCouponService.checkAvailiableCouponsByStoreId(siteId, storeId,userId);
            formatedData.put("coupons", coupons);
            // 第2部分数据，店铺的菜品分类，左侧店铺导航栏
            formatedData.put("foodTypes", foodTypes);
            // 第3部分数据，所有菜品分类和分类下的菜品，第三部分是一个字典，key为菜品分类名称，value为 该分类的菜品列表
            List<JSONObject> allFoods = new ArrayList<>();
            Iterator itr = groupedFoods.values().iterator();
            while (itr.hasNext()) {
                List<JSONObject> oneGroup = (List<JSONObject>)itr.next();
                allFoods.addAll(oneGroup);
            }
            groupedFoods.put(foodTypes.getString(0), allFoods);
            formatedData.put("groupedFoods", groupedFoods);

            return Result.ok(formatedData);
        } else {
            log.error("找不到大厦id：{}，店铺id：{} 的店铺信息", siteId, storeId);
            return Result.error(404, "找不到指定店铺信息");
        }
    }

    /**
     * todo 1.13接口，已废弃， 当联调完成后，删除此部分代码
     * @param siteId
     * @param storeId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "店铺内，点击某个菜品分类，获取该分类的菜品列表", notes="店铺内，点击某个菜品分类，获取该分类的菜品列表")
    @GetMapping("/queryFoodByType")
    public Result<?> queryFoodByType(
            HttpServletRequest request,
            @RequestParam("siteId") String siteId,
            @RequestParam("storeId") String storeId,
            @RequestParam("foodTypeName") String foodTypeName,
            @RequestParam("pageNo") Integer pageNo,
            @RequestParam("pageSize") Integer pageSize) {

        JxStoreRepositoryDo storeRepositoryDo = jxStoreRepositoryMapper.selectById(storeId);
        if (storeRepositoryDo == null) {
            return Result.error("无法从店铺信息中查找到店铺 " + storeId + " 的信息");
        }

        JSONObject resultData = new JSONObject();
        // 此处为 formatedFoods 赋一个默认值，则 queryFoodsByTypeInStorePageInfo 返回结果为0时，最终返回给前端的数据，foods 字段也会是默认值 []
        JSONArray formatedFoods = new JSONArray();
        // 当用户点击 “点菜” 选项 ，或点击 “点菜”选项，并往下滑动，分页调用此接口时，查询菜品的时候，不会去判断 food_type_name 条件，即 “点菜” 匹配所有 类型的菜品
        if (foodTypeName.equalsIgnoreCase("点菜")) {
            foodTypeName = null;
        }

        int totalCount = jxSiteMenuMapper.queryFoodsByTypeInStorePageInfo(siteId, storeId, foodTypeName);
        if (totalCount > 0) {
            formatedFoods = fetchOnePageFoodByType(siteId, storeId, foodTypeName, (pageNo - 1) * pageSize, pageSize);
        }
        resultData.put("total", totalCount);
        int pages = totalCount / pageSize == 0 ? totalCount / pageSize: totalCount / pageSize + 1;
        resultData.put("pages", pages);
        resultData.put("foods",formatedFoods);

        log.info("requestId: {}", request.getAttribute("requestId"));
        log.info("response body: {}", resultData);

        return Result.ok(resultData);
    }

    private JSONArray fetchOnePageFoodByType (String siteId, String storeId, String foodTypeName, Integer pageNo, Integer pageSize) {

        List<HashMap<String,Object>> pageList = jxSiteMenuMapper.queryFoodsByTypeInStoreByPage(siteId, storeId, foodTypeName, pageNo, pageSize);
        JSONArray formatedFoods = buildFoodListInStore(pageList);

        return formatedFoods;
    }

    /**
     * 店铺内有多处地方会展示 符合条件的菜品列表，此方法对数据进行格式化，填充前端页面显示时需要的数据
     * 1. 根据菜品类型 返回菜品列表
     * 2. 店铺内的顶部搜索框，根据搜索条件，返回 菜品列表
     * @param pageList
     * @return
     */
    private JSONArray buildFoodListInStore(List<HashMap<String,Object>> pageList) {
        JSONArray formatedFoods = new JSONArray();
        for (int k = 0 ; k < pageList.size() ; k ++) {
            HashMap<String,Object> oneFoodInfo = pageList.get(k);
            JSONObject formatedFood = new JSONObject();
            formatedFood.put("foodId", oneFoodInfo.get("foodId"));
            formatedFood.put("foodName", oneFoodInfo.get("foodName"));
            formatedFood.put("image", oneFoodInfo.get("foodImage"));
            formatedFood.put("description", oneFoodInfo.get("description"));
            formatedFood.put("specification", JSONObject.parseArray((String)oneFoodInfo.get("specification")));
            formatedFood.put("salePrice",oneFoodInfo.get("salePrice"));
            formatedFood.put("limitCount", oneFoodInfo.get("limitCount"));

            formatedFoods.add(formatedFood);
        }
        return formatedFoods;
    }

    private  JSONObject buildOneFoodInStore(JxSiteMenuDo siteMenuDo, JxFoodRepositoryDo foodRepositoryDo) {

        JSONObject formatedFood = new JSONObject();
        formatedFood.put("foodId", foodRepositoryDo.getId());
        formatedFood.put("foodName", foodRepositoryDo.getFoodName());
        formatedFood.put("image", foodRepositoryDo.getImage());
        formatedFood.put("description", foodRepositoryDo.getDescription());
        formatedFood.put("specification", JSONObject.parseArray(foodRepositoryDo.getSpecification()));
        formatedFood.put("salePrice",siteMenuDo.getStorePrice());
        formatedFood.put("limitCount", siteMenuDo.getLimitCount());

        return formatedFood;
    }
}
